package com.xz.web.controller.supplierOrder;

import com.alibaba.fastjson.JSONObject;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.response.QueryTrackMapResp;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.xz.common.annotation.Log;
import com.xz.common.core.controller.BaseController;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.page.TableDataInfo;
import com.xz.common.core.text.Convert;
import com.xz.common.enums.BusinessType;
import com.xz.common.utils.poi.ExcelUtil;
import com.xz.logistics.service.ILogisticsQueryService;
import com.xz.product.domain.Product;
import com.xz.product.service.IProductService;
import com.xz.purchase.service.IPurchaseProductService;
import com.xz.supplierOrder.domain.SupplierOrder;
import com.xz.supplierOrder.domain.SupplierOrderDetail;
import com.xz.supplierOrder.dto.SupplierOrderDto;
import com.xz.supplierOrder.enums.SupplierOrderStatusEnum;
import com.xz.supplierOrder.service.ISupplierOrderDetailService;
import com.xz.supplierOrder.service.ISupplierOrderProductService;
import com.xz.supplierOrder.service.ISupplierOrderService;
import com.xz.supplierOrder.service.ISupplierOrderTypeFactoryService;
import com.xz.supplierOrder.vo.SupplierOrderDetailVo;
import com.xz.supplierOrder.vo.SupplierOrderVo;
import com.xz.system.service.ISysDictDataService;
import fr.opensagres.odfdom.converter.pdf.internal.BackgroundImage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;

/**
 * 贸易中间商订单Controller
 *
 * @author xz
 * @date 2024-02-27
 */
@RestController
@RequestMapping("/supplier/order")
public class SupplierOrderController extends BaseController {
  @Autowired
  private ISupplierOrderService supplierOrderService;
  @Autowired
  private ISupplierOrderDetailService supplierOrderDetailService;
  @Autowired
  private ISysDictDataService sysDictDataService;
  @Autowired
  private IPurchaseProductService purchaseProductService;
  @Autowired
  private ILogisticsQueryService logisticsQueryService;
  @Autowired
  private ISupplierOrderTypeFactoryService supplierOrderTypeFactoryService;
  @Resource
  private ISupplierOrderProductService supplierOrderProductService;
  @Autowired
  private IProductService iProductService;
  /**
   * 查询贸易中间商订单列表
   */
  //@PreAuthorize("@ss.hasPermi('supplier:order:list')")
  @GetMapping("/list")
  public TableDataInfo list(SupplierOrder supplierOrder) {
    startPage();
    List<SupplierOrder> list = supplierOrderService.selectSupplierOrderList(supplierOrder);
    return getDataTable(list);
  }

  /**
   * 导出贸易中间商订单列表
   */
  //@PreAuthorize("@ss.hasPermi('supplier:order:export')")
  @Log(title = "贸易中间商订单", businessType = BusinessType.EXPORT)
  @GetMapping("/export")
  public AjaxResult export(SupplierOrder supplierOrder) {
    List<SupplierOrder> list = supplierOrderService.selectSupplierOrderList(supplierOrder);
    ExcelUtil<SupplierOrder> util = new ExcelUtil<SupplierOrder>(SupplierOrder.class);
    return util.exportExcel(list, "贸易中间商订单数据");
  }

  /**
   * 获取贸易中间商订单详细信息
   */
  //@PreAuthorize("@ss.hasPermi('supplier:order:query')")
  @GetMapping(value = "/{id}")
  public AjaxResult getInfo(@PathVariable("id") Long id) {
    //订单
    SupplierOrder order = supplierOrderService.selectSupplierOrderById(id);
    SupplierOrderVo orderVo = new SupplierOrderVo();
    if (null != order) {
      BeanUtils.copyProperties(order, orderVo);
      //填充详细信息
      fillingDetails(orderVo);
    }
    return AjaxResult.success(orderVo);
  }

  //填充详细信息
  private void fillingDetails(SupplierOrderVo orderVo) {

    //开始查询商品信息
    List<SupplierOrderDetail> details = supplierOrderDetailService.selectByOrderId(orderVo.getId());
    if (CollectionUtils.isEmpty(details)) {
      return;
    }

    if (3 == orderVo.getOrderType()) {
      int deliveryNum = 0;
      int returnNum = 0;
      for (SupplierOrderDetail detail : details) {
        if (2 == detail.getDataType()) {
          returnNum = returnNum + 1;
        } else {
          deliveryNum = deliveryNum + 1;
        }
      }
      orderVo.setDeliveryNum(deliveryNum);
      orderVo.setReturnNum(returnNum);
    }

    orderVo.setSubtotal(new BigDecimal(0));
    orderVo.setSubtotal2(new BigDecimal(0));

    details.forEach(detail -> {
      SupplierOrderDetailVo vo = new SupplierOrderDetailVo();
      BeanUtils.copyProperties(detail, vo);

     /* Product product = iProductService.getById(vo.getProductId());
      if(null != product) {
        vo.setSeries(product.getSeries());
        vo.setSpecification(product.getSpecification());
      }*/

      if (2 == detail.getDataType()) {
        //如果是退货的数据，则直接添加进vo即可
        orderVo.getReturnDetails().add(vo);
        if(null != detail.getSubtotal()){
          BigDecimal subtract2 = orderVo.getSubtotal2().add(detail.getSubtotal());
          orderVo.setSubtotal2(subtract2);
        }

      } else {
        //如果发货，除了加入vo外，还要考虑状态是否为待发货，如果是则要查询最新的商品库存进行填充
        orderVo.getDeliveryDetails().add(vo);
        if (SupplierOrderStatusEnum.TO_BE_DELIVERY.eq(orderVo.getOrderStatus())) {
          //查询最新的库存信息
          try {
            int availableStock = supplierOrderProductService.countPurchaseProducts(detail);
            vo.setAvailableStock(availableStock);
          }catch (Exception e){
            vo.setAvailableStock(0);
          }
        }
        if(null != detail.getSubtotal()){
          BigDecimal add = orderVo.getSubtotal().add(detail.getSubtotal());
          orderVo.setSubtotal(add);
        }
      }
    });

    if (3 == orderVo.getOrderType()) {
      BigDecimal add = orderVo.getSubtotal().subtract(orderVo.getSubtotal2());
      orderVo.setSubtotal3(add);
      orderVo.setSubtotalStr3(getSubtotalStr(orderVo.getSubtotal3()));
      orderVo.setSubtotalStr2(getSubtotalStr(orderVo.getSubtotal2()));
      orderVo.setSubtotalStr(getSubtotalStr(orderVo.getSubtotal()));
    }else if (2 == orderVo.getOrderType()) {
      orderVo.setSubtotalStr2(getSubtotalStr(orderVo.getSubtotal2()));
    }else if (1 == orderVo.getOrderType()) {
      orderVo.setSubtotalStr(getSubtotalStr(orderVo.getSubtotal()));
    }
    System.out.println();
  }

  private static String getSubtotalStr(BigDecimal number ) {
    return Convert.digitUppercase(number.setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
  }


  /**
   * 新增贸易中间商订单
   */
  //@PreAuthorize("@ss.hasPermi('supplier:order:add')")
  @Log(title = "贸易中间商订单", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@Valid @RequestBody SupplierOrderDto supplierOrder) {
    return toAjax(supplierOrderService.insertSupplierOrder(supplierOrder));
  }

  /**
   * 修改贸易中间商订单
   */
  //@PreAuthorize("@ss.hasPermi('supplier:order:edit')")
  @Log(title = "贸易中间商订单", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit(@Valid @RequestBody SupplierOrderDto supplierOrder) {
    return toAjax(supplierOrderService.updateSupplierOrder(supplierOrder));
  }

  /**
   * 修改状态
   */
  //@PreAuthorize("@ss.hasPermi('supplier:order:edit')")
  @Log(title = "贸易中间商订单", businessType = BusinessType.UPDATE)
  @PutMapping("status")
  public AjaxResult editStatus(@RequestBody SupplierOrderDto order) {
    //校验参数
    if (null == order.getId() || null == order.getOrderStatus()) {
      return error("操作失败，参数异常");
    }

    //目前只支持这两项操作
    if (SupplierOrderStatusEnum.REVERSALED.getStatus() == order.getOrderStatus()) {
      //  冲红操作
      return toAjax(supplierOrderService.reversalOrder(order.getId()));
    } else if (SupplierOrderStatusEnum.NULLIFIED.getStatus() == order.getOrderStatus()) {
      //  作废操作
      return toAjax(supplierOrderService.nullifyOrder(order.getId()));
    }
    return error();
  }

  /** 删除贸易中间商订单 */
  //@PreAuthorize("@ss.hasPermi('supplier:order:remove')")
  //@Log(title = "贸易中间商订单", businessType = BusinessType.DELETE)
  //@DeleteMapping("/{ids}") public AjaxResult remove(@PathVariable Long[] ids) {}


  /**
   * 查询快递信息
   * @param id
   */
  @GetMapping(value = "logistics/{id}")
  public AjaxResult queryLogistics(@PathVariable("id") Long id) {
    //查询订单
    SupplierOrder order = supplierOrderService.selectSupplierOrderById(id);
    if(null == order){
      return AjaxResult.error("订单不存在或已删除");
    }
    //待提交,已废除的订单无法查快递
    if (null == order.getOrderStatus()
      || SupplierOrderStatusEnum.TO_BE_DELIVERY.getStatus() == order.getOrderStatus()
      || SupplierOrderStatusEnum.NULLIFIED.getStatus() == order.getOrderStatus()
    ) {
      return AjaxResult.success(new QueryTrackMapResp());
    }

    //查询物流
    QueryTrackParam param = new QueryTrackParam();
    param.setCom(order.getExpressDeliveryCompanies());//快递公司的编码
    param.setNum(order.getExpressTrackingNumber());//快递单号
    param.setPhone(order.getExpressSenderPhone());//寄件人的电话号码,顺丰的手机号码不能为null；
    param.setTo(order.getAddress());
    // 查询快递信息
    return logisticsQueryService.queryLogisticsByCaptcha(param);
  }

  /**
   * 查询快递信息-调试用
   * @param id
   */
  @GetMapping(value = "logistics/test/{id}")
  public AjaxResult queryTestLogistics(@PathVariable("id") Long id) {
    String test = "{\"message\":\"ok\",\"nu\":\"SF1675568543655\",\"ischeck\":\"1\",\"com\":\"shunfeng\",\"status\":\"200\",\"data\":[{\"time\":\"2024-02-05 10:19:41\",\"context\":\"[北京市]您的快件已由本人签收，如有疑问请电联快递员【何成，电话：13811258124】，感谢您使用顺丰，期待再次为您服务。（主单总件数：2件）\",\"ftime\":\"2024-02-05 10:19:41\",\"areaCode\":\"CN110000000000\",\"areaName\":\"北京\",\"status\":\"签收\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 09:42:40\",\"context\":\"[北京市]快件交给何成，正在派送途中（联系电话：13811258124，顺丰已开启“安全呼叫”保护您的电话隐私,请放心接听！）（主单总件数：2件）\",\"ftime\":\"2024-02-05 09:42:40\",\"areaCode\":\"CN110000000000\",\"areaName\":\"北京\",\"status\":\"派件\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 09:09:38\",\"context\":\"[北京市]快件到达 【北京朝阳金卫路店】\",\"ftime\":\"2024-02-05 09:09:38\",\"areaCode\":\"CN110105000000\",\"areaName\":\"北京,北京,朝阳区\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 08:11:20\",\"context\":\"[北京市]快件离开 【北京顺航中转场】，已在发往 【北京朝阳金卫路店】 的路上\",\"ftime\":\"2024-02-05 08:11:20\",\"areaCode\":\"CN110105000000\",\"areaName\":\"北京,北京,朝阳区\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 08:06:34\",\"context\":\"[北京市]快件在【北京顺航中转场】完成分拣，准备发往 【北京朝阳金卫路店】\",\"ftime\":\"2024-02-05 08:06:34\",\"areaCode\":\"CN110000000000\",\"areaName\":\"北京\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 06:54:38\",\"context\":\"[北京市]快件到达 【北京顺航中转场】\",\"ftime\":\"2024-02-05 06:54:38\",\"areaCode\":\"CN110000000000\",\"areaName\":\"北京\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 06:21:18\",\"context\":\"[北京市]快件离开 【华北航空枢纽北京】，已在发往 【北京顺航中转场】 的路上\",\"ftime\":\"2024-02-05 06:21:18\",\"areaCode\":\"CN110000000000\",\"areaName\":\"北京\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 04:38:42\",\"context\":\"[北京市]快件在【华北航空枢纽北京】完成分拣，准备发往 【北京顺航中转场】\",\"ftime\":\"2024-02-05 04:38:42\",\"areaCode\":\"CN110000000000\",\"areaName\":\"北京\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 04:33:40\",\"context\":\"[北京市]快件到达 【华北航空枢纽北京】\",\"ftime\":\"2024-02-05 04:33:40\",\"areaCode\":\"CN110000000000\",\"areaName\":\"北京\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 03:19:00\",\"context\":\"[北京市]快件到达【北京】，准备发往【华北航空枢纽北京】\",\"ftime\":\"2024-02-05 03:19:00\",\"areaCode\":\"CN110000000000\",\"areaName\":\"北京\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-05 00:42:00\",\"context\":\"[深圳市]快件在【深圳】飞往【北京】顺丰专机上，已起飞\",\"ftime\":\"2024-02-05 00:42:00\",\"areaCode\":\"CN440300000000\",\"areaName\":\"广东,深圳市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 23:53:30\",\"context\":\"[深圳市]快件在【华南航空枢纽深圳】完成分拣，准备发往下一站\",\"ftime\":\"2024-02-04 23:53:30\",\"areaCode\":\"CN440300000000\",\"areaName\":\"广东,深圳市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 23:22:29\",\"context\":\"[深圳市]快件到达 【华南航空枢纽深圳】\",\"ftime\":\"2024-02-04 23:22:29\",\"areaCode\":\"CN440300000000\",\"areaName\":\"广东,深圳市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 21:24:03\",\"context\":\"[珠海市]快件离开 【珠海界涌中转场】，已在发往 【华南航空枢纽深圳】 的路上\",\"ftime\":\"2024-02-04 21:24:03\",\"areaCode\":\"CN440400000000\",\"areaName\":\"广东,珠海市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 20:55:59\",\"context\":\"[珠海市]快件在【珠海界涌中转场】完成分拣，准备发往 【华南航空枢纽深圳】\",\"ftime\":\"2024-02-04 20:55:59\",\"areaCode\":\"CN440400000000\",\"areaName\":\"广东,珠海市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 20:24:30\",\"context\":\"[珠海市]快件到达 【珠海界涌中转场】\",\"ftime\":\"2024-02-04 20:24:30\",\"areaCode\":\"CN440400000000\",\"areaName\":\"广东,珠海市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 19:57:03\",\"context\":\"[珠海市]快件离开 【珠海高新技术产业开发区创新店】，已在发往 【珠海界涌中转场】 的路上\",\"ftime\":\"2024-02-04 19:57:03\",\"areaCode\":\"CN440400000000\",\"areaName\":\"广东,珠海市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 19:37:49\",\"context\":\"[珠海市]快件在【珠海高新技术产业开发区创新店】完成分拣，准备发往 【珠海界涌中转场】\",\"ftime\":\"2024-02-04 19:37:49\",\"areaCode\":\"CN440400000000\",\"areaName\":\"广东,珠海市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 17:36:32\",\"context\":\"[珠海市]快件运输中\",\"ftime\":\"2024-02-04 17:36:32\",\"areaCode\":\"CN440400000000\",\"areaName\":\"广东,珠海市\",\"status\":\"在途\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null},{\"time\":\"2024-02-04 17:05:38\",\"context\":\"[珠海市]顺丰速运 已收取快件\",\"ftime\":\"2024-02-04 17:05:38\",\"areaCode\":\"CN440400000000\",\"areaName\":\"广东,珠海市\",\"status\":\"揽收\",\"areaCenter\":null,\"areaPinYin\":null,\"statusCode\":null}],\"state\":\"3\",\"condition\":\"F00\",\"routeInfo\":{\"from\":{\"number\":\"CN440400000000\",\"name\":\"广东,珠海市\"},\"cur\":{\"number\":\"CN110000000000\",\"name\":\"北京\"},\"to\":{\"number\":\"CN110000000000\",\"name\":\"北京\"}},\"returnCode\":null,\"result\":false,\"trailUrl\":\"https://api.kuaidi100.com/tools/map/5ef86d61d4076f1ba8890c8440d607c8_116.443136,39.921444_5\",\"arrivalTime\":\"2024-02-05 10\",\"totalTime\":\"0天15小时\",\"remainTime\":\"0天0小时\"}";
    QueryTrackResp data = JSONObject.parseObject(test,QueryTrackResp.class);
    return AjaxResult.success(data);
  }
}
